package com.framework;

import java.util.ArrayList;
import java.util.List;

class TransactionManager {
    private List<TransactionalComponent> participants = new ArrayList<>();

    public void register(TransactionalComponent component) {
        participants.add(component);
    }

    public void execute() {
        try {
            // 1. 准备阶段
            for (TransactionalComponent comp : participants) {
                if (!comp.prepare()) {
                    rollback();
                    return;
                }
            }

            // 2. 提交阶段
            for (TransactionalComponent comp : participants) {
                comp.commit();
            }
        } catch (Exception e) {
            rollback();
        }
    }

    public void rollback() {
        for (TransactionalComponent comp : participants) {
            comp.rollback();
        }
    }
}
